//
//  MyUserAccountViewModel.swift
//  weibo08
//
//  Created by 陈杰明 on 16/2/29.
//  Copyright © 2016年 JM. All rights reserved.
//

import UIKit
import SVProgressHUD
class MyUserAccountViewModel: NSObject {
    //定义单例
    static let sharedInstance: MyUserAccountViewModel = MyUserAccountViewModel()
    //用户账户，通过单例全局可以访问
    var userAccount: MyUserAccount?
    
    //用户是否登录
    var userLogin: Bool {
        get{
            return userAccount != nil
        }
    }
    ////保存路径
    let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingString("/account.plist")
    
    private override init() {
    super.init()
        //解档userAccount
        userAccount = loadUserAccount()
    }
    func loadAccessToken(code: String, loadAccessTokenCallBack:(error: NSError?) -> ()) {
        
        MyNetWorkTool.sharedInstance.loadAccessToken(code, accessTokenFinished: { (result, error) -> () in
            //测试错误
//            error = NSError(domain: "1", code: 1, userInfo: nil)
            //判断是否错误
            if result == nil || error != nil {
                
                loadAccessTokenCallBack(error: error)
                return
            }
            print("获取accessToken成功：\(result)")
            //字典转模型
            self.userAccount = MyUserAccount(dict: result!)
            
            //将模型保存到沙盒
            self.saveUserAccount()
            
            //回调获取accesstoken没有错误
            loadAccessTokenCallBack(error: nil)
        })
        
    }
    
    private func saveUserAccount() {
        //判断用户是否有值
        if userAccount != nil {
            
    
//            let accountFile = accountPath! + "/account.plist"
//            print("accountFile \(accountPath)")
            
            NSKeyedArchiver.archiveRootObject(userAccount!, toFile: accountPath)
            
        }
    }
    
    private func loadUserAccount() -> MyUserAccount? {
        //解档
        let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? MyUserAccount
        //判断账户是否过期
//        userAccount?.expriesDate = NSDate(timeIntervalSinceNow: -100)
        if userAccount != nil && userAccount?.expriesDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            print("账户没有过期,\(userAccount?.expriesDate)")
            return userAccount
        }else {
            print("账户过期")
            return nil
        }
    }
    
    func loadUserInfo(loadUserInfoCallBack:(error: NSError?) -> ()) {
        
    MyNetWorkTool.sharedInstance.loadUserInfo { (result, error) -> () in
        if error != nil {
//        print("出错")
        
            loadUserInfoCallBack(error: error)
            return
        }
        
        print("获得数据：\(result)")
        self.userAccount?.screen_name = result?["screen_name"] as? String
        self.userAccount?.avatar_large = result?["avatar_large"] as? String
        
        print("userAccount:\(self.userAccount)")
        self.saveUserAccount()
        
        loadUserInfoCallBack(error: nil)
        }
    }
}
